package com.chanzany.state.case2;

/**
 * @Author ChanZany
 * @Date 2021/10/20 14:39
 * @Version 1.0
 */
//抽象线程状态类
abstract class ThreadState {
    protected String stateName; //状态名
}
//具体状态类：新建状态
class New extends ThreadState{
    public New(){
        this.stateName = "NEW";
        System.out.println("thread in new state.");
    }
    public void start(ThreadContext context){
        System.out.print("call start() method-->");
        if (stateName.equals("NEW")){
            context.setState(new Runnable());
        }else {
            System.out.println("current thread hasn't been new, can not call method start()");
        }

    }
}
//具体状态类：就绪状态
class Runnable extends ThreadState{
    public Runnable(){
        stateName = "RUNNABLE";
        System.out.println("thread in runnable state.");
    }
    public void getCPU(ThreadContext context){
        System.out.print("obtain CPU time-->");
        if (stateName.equals("RUNNABLE")){
            context.setState(new Running());
        }else {
            System.out.println("current thread hasn't been runnable, can not get CPU time");
        }
    }
}
//具体状态类：运行状态
class Running extends ThreadState{
    public Running(){
        stateName = "RUNNING";
        System.out.println("thread in running state.");
    }
    public void suspend(ThreadContext context){
        System.out.print("call suspend() method-->");
        if (stateName.equals("RUNNING")){
            context.setState(new Blocked());
        }else {
            System.out.println("current thread hasn't been running, can not call suspend() method");
        }
    }

    public void stop(ThreadContext context){
        System.out.print("call stop() method-->");
        if (stateName.equals("RUNNING")){
            context.setState(new Dead());
        }else {
            System.out.println("current thread hasn't been running, can not call stop() method");
        }
    }
}

//具体状态类：阻塞状态
class Blocked extends ThreadState{
    public Blocked(){
        stateName = "BLOCKED";
        System.out.println("thread in blocked state.");
    }
    public void resume(ThreadContext context){
        System.out.print("call resume() method-->");
        if (stateName.equals("BLOCKED")){
            context.setState(new Runnable());
        }else {
            System.out.println("current thread hasn't been blocked, can not call resume() method");
        }
    }
}
//具体状态类：死亡状态
class Dead extends ThreadState {
    public Dead() {
        stateName = "DEAD";
        System.out.println("thread in dead state.");
    }
}
